package org.example.netty.dev1.codec;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class RpcEncoder extends MessageToByteEncoder {

    // 目标对象类型进行解码
    private Class<?> target;

    public RpcEncoder(Class<?> target) {
        this.target = target;
    }
    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        System.out.println("222222222222222");
        if(target.isInstance(msg)){
            byte [] data = JSON.toJSONBytes(msg);
            out.writeInt(data.length);// 先将消息长度写入，也就是消息头
            out.writeBytes(data);// 消息体中包含我们要发送的数据
        }
    }
}
